//
//  ResourceRequisitionDB.m
//  Tazama NGO
//
//  Created by jsheriff on 3/25/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "ResourceRequisitionDB.h"
#import "Notifications.h"
#import "Settings.h"

@implementation ResourceRequisitionDB

@synthesize resourceRequisitionList;

static ResourceRequisitionDB *sharedInstance = nil;

+ (ResourceRequisitionDB *)sharedInstance
{
    if (sharedInstance == nil) {
        sharedInstance = [[super allocWithZone:NULL] init];
    }
    return sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedInstance] retain];
}

- (id)init
{
    if ((self = [super init]))
	{
		resourceRequisitionList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}

-(void) addNewResourceRequisition:(ResourceRequisition *)resourceRequisition {
    [resourceRequisitionList addObject:resourceRequisition];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kResourceRequisitionDatabaseUpdateKey object:self userInfo:nil];		    
}

-(void) initWithTestData {
    ResourceRequisition *rr1 = [[ResourceRequisition alloc] init];
	rr1.uuid = CFUUIDCreate(kCFAllocatorDefault);
    rr1.name = @"Bridge Damage";
	rr1.description = @"Check report of bridge damage";
	rr1.location = CLLocationCoordinate2DMake(40.894, 29.801);
//	rr1.location = CLLocationCoordinate2DMake(31.894, 20.201);
	
    [resourceRequisitionList addObject:rr1];
	[rr1 release];
}


-(void)startPollingFeed {
    NSTimer *newTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(pollXmlFeed:) userInfo:nil repeats:YES];
    timer = newTimer;
}

-(void)pollXmlFeed:(NSTimer *)theTimer {
    NSLog(@"Polling XML RR Feed");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *hostName = [defaults objectForKey:kHostName];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/Feeds/COIN1/DEXML?RoleURI=http://%@/ValueLists/Roles/Observers", hostName, hostName]];
//   	NSURL *url = [NSURL URLWithString:@"http://ec2-50-17-89-240.compute-1.amazonaws.com/Feeds/COIN1/DEXML?RoleURI=http://icnet.mitre.org/ValueLists/Roles/Observers"];
	NSString *requestBody = @"";
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setHTTPMethod:@"GET"];
	[request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
	[request setValue:[NSString stringWithFormat:@"%d", [requestBody length]] forHTTPHeaderField:@"Content-Length"];
    request.timeoutInterval = 120.0;
    
    //	NSURLResponse *response;
    //	NSError *error;
    //	[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	receivedData = [[NSMutableData alloc] initWithCapacity:100];
    lastStatusCode = 0;
    theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
	
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
	
    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
    
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        NSLog(@"Status = %d", httpResponse.statusCode);
        lastStatusCode = httpResponse.statusCode;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [theConnection release];
    theConnection = nil;
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
    receivedData = nil;
	
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Receive RR from server" message:@"Failed" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
//    [alert show];
//    [alert release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"connectionDidFinishLoading: Received %d bytes of data",[receivedData length]);
    
    if (lastStatusCode == 200) {
//    if (lastStatusCode == 200 || lastStatusCode == 500) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Receive RR from server" message:@"Succeeded" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
//        [alert show];
//        [alert release];
//        NSString *serverResponse = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
//        NSLog(@"Server Response: %@", serverResponse);
        [self parseResponse:receivedData];
    }
    else {
        NSString *serverResponse = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
        NSLog(@"Server Response: %@", serverResponse);
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Receive RR from server" message:@"Failed" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
//        [alert show];
//        [alert release];
    }
	
    // release the connection, and the data object
    [theConnection release];
    [receivedData release];
}

-(void)parseResponse:(NSData *)responseData {
    if (xmlParser) {
        [xmlParser release];
    }
    
    xmlParser = [[NSXMLParser alloc] initWithData:responseData];
    [xmlParser setDelegate:self];
    [xmlParser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
//	NSLog(@"didStartElement: %@", elementName);
    if ( [elementName isEqualToString:@"rmsg:RequisitionResource"] ) {
        // currentPerson is an ABPerson instance variable
        currentResourceRequisition = [[ResourceRequisition alloc] init];
        return;
    }
	
    // .... continued for remaining elements ....
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (!currentStringValue) {
        // currentStringValue is an NSMutableString instance variable
        currentStringValue = [[NSMutableString alloc] initWithCapacity:50];
    }
    [currentStringValue appendString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    // ignore root and empty elements
//    NSLog(@"didEndElement: %@", elementName);
	
    if ([elementName isEqualToString:@"rmsg:RequisitionResource"]) {
        // addresses and currentPerson are instance variables
        for (ResourceRequisition *rr in [ResourceRequisitionDB sharedInstance].resourceRequisitionList) {
            if (CFEqual(rr.uuid, currentResourceRequisition.uuid)) {
                [currentResourceRequisition release];
                return;
            }
        }
        [self addNewResourceRequisition:currentResourceRequisition];
        [currentResourceRequisition release];
        return;
    }
    
	if ([elementName isEqualToString:@"rmsg:Name"]) {
		currentResourceRequisition.name = currentStringValue;
	}
	else if ([elementName isEqualToString:@"rmsg:Description"]) {
		currentResourceRequisition.description = currentStringValue;
	}
	else if ([elementName isEqualToString:@"rmsg:MessageID"]) {
        currentResourceRequisition.uuid = CFUUIDCreateFromString(NULL, (CFStringRef)currentStringValue);
	}
	else if ([elementName isEqualToString:@"gml:pos"]) {
        NSArray *values = [currentStringValue componentsSeparatedByString:@" "];
        if (values.count == 2) {
            NSString *latitudeString = [values objectAtIndex:0];
            NSString *longitudeString = [values objectAtIndex:1];
            currentResourceRequisition.location = CLLocationCoordinate2DMake([latitudeString doubleValue], [longitudeString doubleValue]);
            NSLog(@"New Resource Requisition.  latitude = %2.4f, longitude = %3.4f", currentResourceRequisition.location.latitude, currentResourceRequisition.location.longitude);
        }
	}
    
	// currentStringValue is an instance variable
    [currentStringValue release];
    currentStringValue = nil;
}

- (oneway void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

@end
